﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Phone.Framework;
using System.Collections.Generic;
using CetWin.Phone.Entity;
using Phone.Framework.Threads;
using PF = Phone.Framework;
using System.Linq;
using Microsoft.Phone.Controls;
using System.Threading;
using Caliburn.Micro;
using CetWin.Phone;
using CetWin.Phone.Services;
using Microsoft.Phone.Shell;
using Phone.Framework.CaliburnExtensions.Results;
using Phone.Framework.CaliburnExtensions;
using System.Collections;
namespace CetWin.ViewModels
{

    public class MainPageViewModel : Screen, IHandle<HandleMessage>
    {
        private readonly INavigationService navigationService;
        private readonly WordService _wordService;
        private readonly HistoryService _historyService;
        private IList<Word> _list;
        private DelayTimer _delayTimer = new DelayTimer();
        private CetWinSetting _setting;
        private string[] chars;
        public MainPageViewModel(INavigationService navigationService,
            HistoryService historyService, WordService wordService)
        {
            this.navigationService = navigationService;
            _historyService = historyService;
            _wordService = wordService;
            Initialize();
        }

        public void Initialize()
        {
            var wordStatistics = IoC.Get<WordStatistics>();
            _setting = IoC.Get<CetWinSetting>();
            ThreadManager.Instance.TaskWithLoading(() =>
            {
                WordIOService io = new WordIOService();
                _list = io.LoadFromText1();

                LoadWordLibrary(string.Empty);
                //if (!string.IsNullOrEmpty(IoC.Get<CetWinSetting>().SelectedWordLibrary))
                //{
                //    LoadWordLibrary(IoC.Get<CetWinSetting>().SelectedWordLibrary);
                //}
            });
          
           
            IoC.Get<IEventAggregator>().Subscribe(this);

            _delayTimer.InitInvoke(0.55, InternalSearch);

            chars = AlphaHelper.GetAlphas();
        }

        private void LoadWordLibrary(string libraryName)
        {
            var wordStatistics = IoC.Get<WordStatistics>();
            ThreadManager.Instance.TaskWithLoading(() =>
            {
                WordIOService io = new WordIOService();

                var cet4 = io.LoadLibrary("cet4");
                var cet6 = io.LoadLibrary("cet6");
                var dict = _list.ToDictionary(e => e.Name);
                //UIThread.Invoke(() =>
                //{
                //    wordStatistics.TotalCount = _list.Count;
                //    wordStatistics.Cet4LibraryWordCount = cet4.Count;
                //    wordStatistics.Cet6LibraryWordCount = cet6.Count;
                //    //wordStatistics.LibraryName = libraryName;
                //    //IoC.Get<CetWinSetting>().SelectedWordLibrary = libraryName;
                //});
                //var level =Convert.ToInt32(libraryName.Substring(3, 1));
                foreach (var item in cet4)
                {
                    if (dict.ContainsKey(item.Name))
                    {
                        dict[item.Name].IsCet4Level = true;
                        dict[item.Name].CetLevel = 4;
                    }
                   
                }
                foreach (var item in cet6)
                {
                    if (dict.ContainsKey(item.Name))
                    {
                        dict[item.Name].IsCet6Level = true;
                        dict[item.Name].CetLevel = 6;
                    }
                }
                SortWordList(_setting.SearchPriority);
            });
        }

        private void SortWordList(string sortName)
        {
            switch (sortName)
            {
                case "Normal":
                    _list = _list.OrderBy(e=>e.Name).ToList();
                    break;
                case "CET4":
                    _list =_list.OrderBy(e=>e.CetLevel).Where(e => e.CetLevel >= 4).Union(_list.Where(e => e.CetLevel == 0)).ToList();
                    break;
                case "CET6":
                    _list = _list.OrderByDescending(e => e.CetLevel).ThenBy(e => e.IsCet6Level).ToList();
                    break;
                default:
                    break;
            }
        }

        public void SelectWordLibrary(ListPicker picker)
        {
            if (picker.SelectedItems.Count > 0)
            {
                var selectedItem = picker.SelectedItems[0].ToString();
                LoadWordLibrary(selectedItem);
            }
        }

        protected override void OnActivate()
        {
            if (_list != null)
                ResultHelper.Execute(new LoadedResult());
            base.OnActivate();
        }

        #region Event

        public void OnTap()
        {
            SearchDetail();
        }

        public void OnSearchKeyUp(KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                SearchDetail();
            }
        }

        #endregion

        #region Property

        public string ItemTemplate
        {
            get { return _setting.WordItemTemplate; }
        }

        //public string SelectedWordLibrary
        //{
        //    get { return _setting.SelectedWordLibrary; }
        //    set
        //    {
        //        if (_setting.SelectedWordLibrary != value)
        //        {
        //            _setting.SelectedWordLibrary = value;
        //            NotifyOfPropertyChange("SelectedWordLibrary");
        //        }
        //    }
        //}

        private string _searchText;

        public string SearchText
        {
            get { return _searchText; }
            set
            {
                if (_searchText != value)
                {
                    _searchText = value;
                    NotifyOfPropertyChange("SearchText");
                    SearchWord();
                }
            }
        }

        private Word _selectedWord;

        public Word SelectedWord
        {
            get { return _selectedWord; }
            set
            {
                _selectedWord = value;
                NotifyOfPropertyChange("SelectedWord");
                NotifyOfPropertyChange(() => CanSearchDetail);
                NotifyOfPropertyChange(() => CanAddToHistory);
                if (value != null)
                    CanSwitchHistoryIcon = _historyService.Contains(value.Name);
                else
                    CanSwitchHistoryIcon = false;
            }
        }

        private bool _canSwitchHistoryIcon;
        public bool CanSwitchHistoryIcon
        {
            get { return _canSwitchHistoryIcon; }
            set
            {
                _canSwitchHistoryIcon = value;
                NotifyOfPropertyChange(() => CanSwitchHistoryIcon);
            }
        }

        private IEnumerable<Word> _searchResult;
        public IEnumerable<Word> SearchResult
        {
            get { return _searchResult; }
            set
            {
                _searchResult = value;
                NotifyOfPropertyChange("SearchResult");
            }
        }

        #endregion

        #region Method

        public void SearchWord()
        {
            _delayTimer.AddObj(SearchText);
        }

        public IEnumerable<IResult> SearchNetworkWord()
        {
            if (_list == null) return null;
            if (SelectedWord != null || string.IsNullOrEmpty(SearchText) || _list.Any(e => e.Name == SearchText))
                return null;


            return ResultHelper.Action((IActionResult result) =>
            {
                _wordService.AsyncAddNetWord(SearchText, (Word word) =>
                {
                    if (word != null)
                    {
                        _list.Add(word);
                        UIThread.Invoke(() =>
                        {
                            SearchWord();
                            result.Set();
                        });
                    } else
                        result.Set();
                });
            });
        }

        public bool CanSearchDetail
        {
            get
            {
                return SelectedWord != null;
            }
        }

        public void SearchDetail()
        {
            if (SelectedWord == null) return;
            PhoneStateManager.SetAppState(GlobalConstant.SelectedWordField, SelectedWord);
            navigationService.UriFor<WordDetailViewModel>().
                WithParam(x => x.SearchText, SelectedWord.Name)
                .Navigate();
        }

        public bool CanAddToHistory
        {
            get
            {
                return CanSearchDetail;
            }
        }

        public void AddToHistory()
        {
            ThreadManager.Instance.AddTask(() =>
            {
                _historyService.SaveHistory(SelectedWord.Name, CanSwitchHistoryIcon);
            });

            CanSwitchHistoryIcon = !CanSwitchHistoryIcon;
        }

        //public IEnumerable<IResult> AddToHistory()
        //{
        //    return ResultHelper.AppButtonAction((IActionResult result) =>
        //    {
        //        ThreadManager.Instance.AddTask(() =>
        //        {
        //            if (CanSwitchHistoryIcon)
        //            {
        //                _historyService.DeleteHistory(SelectedWord.Name);
        //            }
        //            else
        //            {
        //                _historyService.AddHistory(SelectedWord.Name);
        //            }
        //        }, () => {
        //            CanSwitchHistoryIcon = !CanSwitchHistoryIcon;
        //            result.Set();
        //        });
        //        //if (CanSwitchHistoryIcon)
        //        //{
        //        //    _historyService.DeleteHistory(SelectedWord.Name);
        //        //}
        //        //else
        //        //{
        //        //    _historyService.AddHistory(SelectedWord.Name);
        //        //}
        //        //CanSwitchHistoryIcon = !CanSwitchHistoryIcon;
        //        //result.Set();
        //    });
        //}

        public void OpenHistoryView()
        {
            navigationService.UriFor<HistoriesViewModel>().Navigate();
        }

        public void OpenCategoryView()
        {
            navigationService.UriFor<CategoryViewModel>().Navigate();
        }

        public void OpenAboutView()
        {
            navigationService.UriFor<AboutViewModel>().Navigate();
        }

        public void OpenLogView()
        {
            navigationService.UriFor<LogViewModel>().Navigate();
        }

        public void OpenSettingsView()
        {
            navigationService.UriFor<SettingsViewModel>().Navigate();
        }

        public void InternalSearch(object key)
        {
            if (_list == null) return;
            if (string.IsNullOrEmpty(SearchText))
            {
                SearchResult = null;
                SelectedValue = SearchText;
                return;
            }
            ThreadManager.Instance.AddTask(() =>
            {
                IEnumerable<Word> list = null;
                foreach (var item in SearchText)
                {
                    if (!chars.Contains(item.ToString().ToLower()))
                    {
                        list = _list
                            .Where(e => WordSearchEngineFactory.FilerChinese(SearchText, e.Explain)).Take(_setting.SearchResultCount);

                        UIThread.Invoke(() => {
                            SearchResult = list;
                        });
                        return;
                    }
                }

               list = _list.Where(
                    WordSearchEngineFactory.GetWordSearch(SearchText.Trim(), _setting.IsCaseSensitive)).
                    Take(_setting.SearchResultCount).ToList();
                UIThread.Invoke(() =>
                {
                    SearchResult = list;
                    SelectedValue = SearchText;
                });
                 
            });
        }

        private string _selectedValue;
        public string SelectedValue
        {
            get { return _selectedValue; }
            set
            {
                _selectedValue = value;
                NotifyOfPropertyChange(() => SelectedValue);
                _selectedValue = string.Empty;
            }
        }

        private bool _canPlayVoice = true;
        public bool CanPlayVoice
        {
            get { return _canPlayVoice; }
            set
            {
                _canPlayVoice = value;
                NotifyOfPropertyChange(() => CanPlayVoice);
            }
        }

        public void PlayVoice(Word word)
        {
            CanPlayVoice = false;
            if (word.Audio == null)
            {
                ResultHelper.Execute(LoadingResult.Default());
                _wordService.AsyncUpdateNetWord(word, () =>
                {
                    ResultHelper.Execute(new LoadedResult());
                    IoC.Get<IMediaPlayService>().Play(word.Audio, () => { CanPlayVoice = true; });
                });
            }
            else
            {
                IoC.Get<IMediaPlayService>().Play(word.Audio, () => { CanPlayVoice=true; });
            }
        }

        #endregion

        public bool ShowWarnWhenExit
        {
            get { return _setting.ShowWarnWhenExit; }
        }

        public void Handle(HandleMessage message)
        {
            switch (message.Message)
            {
                case Messages.UpdateSetting:
                    SortWordList(_setting.SearchPriority);
                    NotifyOfPropertyChange(() => ItemTemplate);
                    NotifyOfPropertyChange(() => ShowWarnWhenExit);
                    SearchWord();
                    break;
                case Messages.UpdateHistroy:
                    CanSwitchHistoryIcon = !CanSwitchHistoryIcon;
                    break;
            }
        }
    }
}